package com.atzongmaotan.reggie.controller;

import com.atzongmaotan.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * ClassName:    CommonController
 * Package:  com.atzongmaotan.controller
 * Description:
 *
 * @Author: interface
 * @Create: 2024/6/14 - 上午6:23
 * @Version: v1.0
 */
@RestController
@Slf4j
@RequestMapping("common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    @PostMapping("upload")
    public R<String> upload(MultipartFile file) {
        log.info("文件上传");
        String originalFileName = file.getOriginalFilename();
        //获取文件后缀
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString()+suffix;
        //判断目录是否存在,不存在则进行创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }
    @GetMapping("download")
    public void download(String fileName, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        FileInputStream fis = null;
        ServletOutputStream outputStream = null;
        try {
            //获取输入流
            fis = new FileInputStream(new File(basePath+fileName));
            //获取输出流
            outputStream = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = fis.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
